import { removeToken } from '@/utils/auth'
import { loginOut } from '@/views/login/api'
import { getUserInfo } from '@/views/login/api'
import { systemCode } from '@/utils/config'
import watermark from '@/utils/water'
import useTagsStore from './tagsView'
import $api from '@/api/commonApi'
import cache from '@/plugins/cache'
type userInfo = {
  id: number
  userId: string
  userName: string
  avatar: string
  [key: string]: unknown
}
const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: {} as userInfo,
    qiniuInfo: null as any
  }),
  actions: {
    setUserInfo(obj: any) {
      this.userInfo = obj
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        const userInfo = cache.local.getJSON('debtUserInfo', true)
        if (userInfo) {
          resolve(userInfo)
        } else {
          resolve(this.getInfoData())
        }
      })
    },
    // 获取七牛云token
    getQiniu() {
      return new Promise((resolve, reject) => {
        if (this.qiniuInfo) {
          resolve(this.qiniuInfo)
        } else {
          $api.getQiniu().then((res: any) => {
            if (res.code === '200000') {
              this.qiniuInfo = res.data
              resolve(this.qiniuInfo)
            }
          })
        }
      })
    },
    // 通过接口获取用户信息
    getInfoData() {
      return new Promise((resolve, reject) => {
        getUserInfo<any>({ systemCode })
          .then((res) => {
            const { id, userId, employeeId, userName, userType, areaCode } = res.data
            const userInfo = {
              id,
              userId,
              employeeId,
              userName,
              userType,
              areaCode
            }
            cache.local.setJSON('debtUserInfo', userInfo, true)
            cache.local.setJSON('menuRoutes', res.data.menus)
            this.setUserInfo(userInfo)
            resolve(userInfo)
          })
          .catch(() => {
            reject()
          })
      })
    },
    // 退出系统
    logOut() {
      return new Promise((resolve) => {
        loginOut()
          .then(() => {
            this.loginOut()
            resolve(true)
          })
          .catch(() => {
            resolve(true)
          })
      })
    },
    // 退出系统,不调用接口
    loginOut() {
      cache.local.remove('debtUserInfo')
      cache.local.remove('menuRoutes')
      useTagsStore().resetView()
      removeToken()
      watermark.out()
    }
  }
})

export default useUserStore
